package com.security.config;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @author ZhangJunqi
 * @Date 2022/3/5 -9:38
 */
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //新版本是authorizeHttpRequests可点进去看方法
        http.authorizeRequests ()
                .antMatchers ("/").permitAll ()
                .antMatchers ("/level1/**").hasRole ("VIP1")
                .antMatchers ("/level2/**").hasRole ("VIP2")
                .antMatchers ("/level2/**").hasRole ("VIP3");
        //设置登录界面，默认界面是url=login，可以设置自定义登录界面对应controller跳转登录的toLogin
        //登录界面的登录跳转的input组件默认name=username和password可以自定义name
        //登录界面的跳转url必须也是修改后的toLogin,或者通过loginProcessingUrl修改
        http.formLogin ().usernameParameter ("userName").passwordParameter ("password").loginPage ("/toLogin").loginProcessingUrl ("/login");

        http.csrf ().disable ();//退出失败时关闭防止跨站请求
        http.logout ().logoutSuccessUrl ("/");
        //添加记住我，在自定义登录添加remember的复选框
        http.rememberMe ().rememberMeParameter ("remember");
        ///formLogin(); 无权限默认跳转地址"login", "POST
        //注销并跳转Index页面
    }

    //认证  在spring2.1.x版本可以直接使用，否则需要对password进行加密
    //注意用户名不要纯数字
    //密码加密实现PasswordEncoder接口
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        String[] role={"VIP1","VIP2","VIP3"};
        auth.inMemoryAuthentication ()
                .passwordEncoder (new BCryptPasswordEncoder ())
                .withUser ("zhang").password (new BCryptPasswordEncoder ().encode ("123")).roles ("VIP1")
                .and ()
                .withUser ("chao").password (new BCryptPasswordEncoder().encode ("123")).roles ("VIP1","VIP2")
                .and ()
                .withUser ("admin").password (new BCryptPasswordEncoder ().encode ("123")).roles (role);
        //当spring版本为2.0.9.RELEASE时，一次只能使用一种加密方式  BCryptPasswordEncoder  LdapShaPasswordEncoder   Pbkdf2PasswordEncoder
    }
}
